'''
模拟实盘任务管理
'''
import collections
import datetime
from module.api.R import R

from module.common.common import getAfterday
from module.thread.ThreadManager import ThreadManager

from module.const.Constant import const
from module.utils import TaskAdminUtil

import logging
log = logging.getLogger("weblog")

class SimulaterTaskAdmin(object):
    # def __init__(self):
        # 模拟实盘任务Map: key-taskid, [ShortOptionDetail, status, tasklist]
        # 0-任务加载中/1-运行中/2-手动暂停/3-执行成功/4-执行异常失败
        # self.simulaterTaskMap = collections.defaultdict(list)

    def taskStart(self, uuid, taskid, shortOptionDetail):
        taskCenter = TaskAdminUtil.pullTaskCenter(taskid)
        if taskCenter:
            if taskCenter[1] == const.TASK_STATUS_RUNNING:
                return R().error("任务仍在运行中，重启请先暂停")
            elif taskCenter[1] == const.TASK_STATUS_LOADING:
                return R().error("任务正在拼命中，重启请先暂停")

        shortOptionDetail['taskid'] = taskid
        taskCenter = [shortOptionDetail, 0, []]
        TaskAdminUtil.pushTaskCenter(taskid, taskCenter)

        code = shortOptionDetail['code'][0]
        stockname = shortOptionDetail['stock_name'][0]
        shortOptionDetail['uuid'] = "%s%s" % (code, uuid)

        tasklist = []   # 具体任务列表，包括开单和平单
        openDT = shortOptionDetail['datetime1']
        openRiqi = openDT[:10]
        openStarttime = str(datetime.datetime.strptime(openDT, '%Y-%m-%d %H:%M:%S') - datetime.timedelta(minutes=5))
        openEndtime = str(datetime.datetime.strptime(openDT, '%Y-%m-%d %H:%M:%S') + datetime.timedelta(minutes=5))
        opentask = [code, openRiqi, openStarttime, openEndtime, 0, stockname]
        tasklist.append(opentask)

        closeDT = shortOptionDetail['datetime2']
        closeRiqi = closeDT[:10]
        closeStarttime = str(datetime.datetime.strptime(closeDT, '%Y-%m-%d %H:%M:%S') - datetime.timedelta(minutes=5))
        closeEndtime = str(datetime.datetime.strptime(closeDT, '%Y-%m-%d %H:%M:%S') + datetime.timedelta(minutes=5))
        closetask = [code, closeRiqi, closeStarttime, closeEndtime, 0, stockname]
        tasklist.append(closetask)

        taskCenter[2] = tasklist
        manager = ThreadManager(taskCenter)
        manager.assignTask()
        log.info("api交互调度开启了任务：%s" % tasklist)
        return R().ok()

    def taskStop(self, taskid):
        taskCenter = TaskAdminUtil.pullTaskCenter(taskid)
        if not taskCenter:
            return R().error("任务不存在，无法暂停")
        elif taskCenter[1] == 2:
            return R().error("任务已经手动暂停")

        taskCenter[1] = const.TASK_STATUS_STOP
        # for minitask in taskCenter[2]:
        #     if minitask[4] == const.TASK_STATUS_LOADING or minitask[4] == const.TASK_STATUS_RUNNING:
        #         minitask[4] = const.TASK_STATUS_STOP
        log.info("api交互调度暂停了任务：%s" % taskCenter[2])
        return R().ok()

    def taskRenew(self, taskid, shortOptionDetail):
        taskCenter = TaskAdminUtil.pullTaskCenter(taskid)
        if not taskCenter:
            return R().error("任务不存在，无法更新配置")
        elif taskCenter[1] == const.TASK_STATUS_STOP:
            return R().error("任务已经手动暂停")

        shortOptionDetail['taskid'] = taskid
        taskCenter[0] = shortOptionDetail
        return R().ok()

    def taskInfo(self, taskid):
        taskCenter = TaskAdminUtil.pullTaskCenter(taskid)
        if not taskCenter:
            return R().error("任务不存在，无任务状态")

        statusData = {'runState': '初始化中'}
        if taskCenter[1] == const.TASK_STATUS_LOADING:
            statusData['runState'] = '任务加载中'
        elif taskCenter[1] == const.TASK_STATUS_RUNNING:
            statusData['runState'] = '运行中'
        elif taskCenter[1] == const.TASK_STATUS_STOP:
            statusData['runState'] = '手动暂停'
        elif taskCenter[1] == const.TASK_STATUS_DONE:
            statusData['runState'] = '执行完成'
        elif taskCenter[1] == const.TASK_STATUS_EXCEPT:
            statusData['runState'] = '执行异常'
        else:
            statusData['runState'] = '未知状态'
        log.info("api交互查询任务详情信息：%s" % taskCenter)
        return R().ok2('获取转态成功', statusData)

    def taskDetailInfo(self, taskid):
        taskCenter = TaskAdminUtil.pullTaskCenter(taskid)
        if not taskCenter:
            return R().error("任务不存在，无任务状态")

        detaiDta = {}
        detaiDta['detail'] = taskCenter
        return R().ok2('获取详情成功', detaiDta)
